package com.lu.task.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.lu.common.utils.*;
import com.lu.system.management.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.lu.task.domain.TaskDO;
import com.lu.task.service.TaskService;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 
 * @author showlu
 * @email 1309617271@qq.com
 * @date 2018-08-16 18:55:10
 */
 
@RestController
@RequestMapping("/mail/task")
public class TaskController {
	@Autowired
	private TaskService taskService;

   /**
    *  根据id查询
	*  @return
	*/
    @ResponseBody
    @GetMapping("/get")
    public R get(Long id){
        TaskDO task = taskService.get(id);
        R r = new R();
        r.put("data",task);
        return r;
    }

	/**
	 * 查询列表数据
	 * @param params
	 * @return
	 */
	@ResponseBody
	@GetMapping("/list")
	public PageUtils getTaskList(@RequestParam Map<String, Object> params){
        Query query = new Query(params);
		List<TaskDO> taskList = taskService.list(query);
		int total = taskService.count(query);
		PageUtils pageUtils = new PageUtils(taskList, total);
		return pageUtils;
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save( TaskDO task){
		if(taskService.save(task)>0){
			return R.ok();
		}
		return R.error();
	}

    /**
     * 批量保存
     */
    @ResponseBody
    @PostMapping("/saveBatch")
    public R saveBatch( List<TaskDO> task){
        try {
			taskService.saveBatch(task);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update( TaskDO task){
		taskService.update(task);
		return R.ok();
	}

    /**
     * 批量修改
     */
    @ResponseBody
    @PostMapping("/updateBatch")
    public R updateBatch( List<TaskDO> task){
        try {
			taskService.updateBatch(task);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
        return R.ok();
    }

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	public R remove( Long id){
		if(taskService.remove(id)>0){
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 批量删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") Long[] ids){
		taskService.batchRemove(ids);
		return R.ok();
	}

	@GetMapping("/getOrderJobList")
	public PageUtils getOrderJobList(String orderSyncRuleData,Integer page,Integer limit,HttpServletRequest request){

		Map<String, Object> map = JSONUtils.jsonToMap(orderSyncRuleData);

		UserDO userDO = null;
		try {
			userDO = TokenUtils.parseJwtForUserInfo(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(map==null){
			map = new HashMap<>();
		}
		//不是系统管理员的账户需要只能看到自己的任务
		if(!userDO.getUserId().equals(1L)){
			map.put("userId",userDO.getUserId());
		}
		PageUtils taskLists = null;
		try {
			taskLists = taskService.getTaskList(map,page,limit);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return taskLists;
	}

	/**
	 * 保存
	 */
	@PostMapping("/saveJob")
	public R saveJob(@RequestParam String quartzTaskRuleData, HttpServletRequest request) throws Exception {
		UserDO userDO = null;
		try {
			userDO = TokenUtils.parseJwtForUserInfo(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		TaskDO task = JSON.parseObject(quartzTaskRuleData,TaskDO.class);
		if(task==null){
			return R.error();
		}
		Map<String,Object> map = new HashMap<>();
		map.put("jobGroup",task.getJobGroup());
		map.put("jobName",task.getJobName());
		List<TaskDO> lists = taskService.list(map);
		if(lists.size()>0){
			return R.error("不可重复添加,在"+task.getJobGroup()+"任务组中，已存在"+task.getJobName()+"任务");
		}
		Integer res = taskService.saveJob(task,userDO);
		if(res==null){
			return R.error();
		}
		return R.ok();
	}


	/**
	 * 删除
	 */
	@PostMapping("/removeJob")
	public R removeJob(Long id) throws Exception{
		Integer res = taskService.removeJob(id);
		if(res==null){
			return R.error();
		}
		return R.ok();
	}

	/**
	 * 修改
	 */
	@PostMapping("/updateJob")
	public R updateJob(String quartzTaskRuleData) throws Exception {
		TaskDO task = JSON.parseObject(quartzTaskRuleData,TaskDO.class);
		if(task==null){
			return R.error();
		}
		Integer res = taskService.updateJob(task);
		if(res==null){
			return R.error();
		}
		return R.ok();
	}

	/**
	 *  是否启用任务（修改状态）
	 */
	@GetMapping("/updateJobStatus")
	public R updateJobStatus(Long jobId, String cmd){
		try {
			taskService.changeStatus(jobId,cmd);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return R.error();
		}
		return R.ok();
	}
	
}
